﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AzureProvider.ssdsClient;

namespace AzureProvider.SoupMethods
{

    public class PostCategory
    {
        public string Id;
        public Guid PostId;
        public Guid CategoryId;
    }

    public class PostCategoryMethods : PostRelatedMethods
    {

        protected override string containerId
        {
            get { return "Posts"; }
        }

        protected override string kind
        {
            get { return "PostCategory"; }
        }

        protected override Entity CreateEntity(object Object)
        {
            PostCategory myobj = (PostCategory)Object;

            var entity = new Entity()
            {
                Id = myobj.Id ,
                Kind = kind
            };

            entity.Properties = new Dictionary<string, object>();
            entity.Properties.Add("CategoryId", myobj.CategoryId.ToString());
            entity.Properties.Add("PostId", myobj.PostId.ToString());

            return entity;
        }

        public override object CreateObject(Entity Entity)
        {
            PostCategory myObj = new PostCategory();
            myObj.Id = Entity.Id;
            myObj.CategoryId = new Guid((string)Entity.Properties.Single(tt => tt.Key == "CategoryId").Value);
            myObj.PostId = new Guid((string)Entity.Properties.Single(tt => tt.Key == "PostId").Value);

            return myObj;
        }

        private string GetId(string PostId, Guid  CategoryId)
        {
            string errMessage;
            PostCategory myobj =
                GetPostCategories(PostId, out errMessage).SingleOrDefault(p => p.CategoryId == CategoryId);
            if (myobj != null)
                return myobj.Id;
            else
                return Guid.NewGuid().ToString();

        }
        public PostCategory[] CreatePostCategory(string PostID, BlogEngine.Core.Category[] Categories)
        {
            List<PostCategory> pt = new List<PostCategory>();
            foreach (BlogEngine.Core.Category Cat in Categories)
            {
                if (Cat != null)
                {
                    pt.Add(new PostCategory
                    {
                        Id = GetId(PostID,Cat.Id) ,
                        PostId = new Guid(PostID),
                        CategoryId = Cat.Id
                    });
                }
            }
            return pt.ToArray();
        }

        public IEnumerable<PostCategory> GetPostCategories(string PostId, out string errMessage)
        {
            string qry = null;
            if (PostId != null)
                qry = string.Format(" from e in entities where e.Kind == \"{0}\" && e[\"PostId\"] == \"{1}\"  select e", kind, PostId);
            return base.GetObjects(qry, out errMessage).Cast<PostCategory>();
        }

       

    }
}
